<template>
  <div>
    <h1>续签合同</h1>
    <el-card shadow="never">
      <p>基本信息</p>
      <el-form label-width="100px" @submit.native.prevent="save">
        <el-row>
          <el-col :span="8">
            <el-form-item label="合同编号">
              <el-input v-model="model.contractNumber"></el-input>
            </el-form-item>
            <el-form-item label="摊位名称">
              <!-- <el-input v-show="qwe" @focus="abc" v-model="model.stallName"></el-input> -->
              <my-select
                ref="mySelectStallName"
                url="api/v1/backend/public/stall"
                :isMultiple="true"
                :queryParamers="{status: 0}"
                @selected="mySelectedStall"
              ></my-select>
            </el-form-item>
            <!-- <el-form-item label="所属区域名称">
              <el-input v-model="model.partitionName"></el-input>
            </el-form-item>-->
            <el-form-item label="签订日期">
              <el-date-picker
                size="small"
                style="margin: 0 0 20px 0;"
                @change="changeSignDate"
                v-model="model.signDate"
                type="date"
                placeholder="选择签订日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="到期时间">
              <el-date-picker
                size="small"
                style="margin: 0 0 20px 0;"
                @change="changeDueTime"
                v-model="model.dueTime"
                type="date"
                placeholder="选择到期时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="选择商户">
              <my-select
                ref="mySelectBusiness"
                url="api/v2/backend/market/contract/choice_business"
                @selected="mySelectedBusiness"
              ></my-select>
            </el-form-item>
            <el-form-item label="联系人">
              <el-input v-model="model.personInCharge"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="model.phone"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="model.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同图片">
              <el-upload
                class="avatar-uploader"
                ref="photoUrl"
                style="display: inline-block;"
                action="https://upload.qiniup.com"
                :on-remove="handleRemove"
                :on-success="handleSuccessphotoUrl"
                :data="uploadToken"
                :before-upload="beforeUpload"
                list-type="picture-card"
              >
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="queryimg">
                <!-- <img v-for="(item,index) in model.contractPhoto" :src="item.photoUrl" :key="index" class="avatar" >-->
                <!-- {{model.contractPhoto}} -->
                <template v-for="(item,index) in model.contractPhoto">
                  <div class="imgfile" :key="index">
                    <i
                      class="el-icon-document"
                      @click="imgshow(index)"
                      v-if="ishidden!=item.keyindex"
                    >合同照片{{item.keyindex}}</i>
                    <i
                      class="el-icon-delete"
                      style="margin-left:20px;color:red"
                      @click="imgdelete(item.keyindex,index)"
                      v-if="ishidden!=item.keyindex"
                    ></i>
                  </div>
                </template>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <p style="margin: 50px 0 30px;font-size: 16px;">
          <span style="color: #f65f2f;border: 3px solid #004e66; margin-right: 10px;"></span>
          收费相关
        </p>

        <el-row>
          <el-col :span="12">
            <p style="font-size: 14px;">
              收费项目
              <el-button @click="addpayment" type="primary" size="mini">新增</el-button>
            </p>

            <el-dialog :visible.sync="dialogVisible" width="45%">
              <!-- <p style="font-size: 20px;">新增{{paymentName}}</p> -->
              <el-form :model="tableModel" label-width="110px">
                <el-form-item label="收费项目：" prop="paymentTypeName">
                  <el-select
                    v-model="tableModel.paymentTypeName"
                    @change="changePaymentType"
                    placeholder="请选择"
                    size="small"
                  >
                    <el-option
                      v-for="item in paymentTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="单价：" prop="price">
                  <el-input v-model="tableModel.price" size="small"></el-input>
                </el-form-item>
                <el-form-item label="单位：" prop="unit">
                  <el-input v-model="tableModel.unit" size="small"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">不修改{{paymentName}}项目</el-button>
                <el-button type="primary" @click="saveArray">新增{{paymentName}}项目</el-button>
              </span>
            </el-dialog>
            <el-table :data="tableArray" style="width: 85%">
              <el-table-column prop="paymentTypeName" label="收费项目"></el-table-column>
              <el-table-column prop="price" label="单价"></el-table-column>
              <el-table-column prop="unit" label="单位"></el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <!-- <el-button @click="paymentEdit(scope.row)" type="text" size="small">编辑</el-button> -->
                  <el-button
                    @click.native.prevent="paymentDelete(scope.$index, tableArray)"
                    style="color:#dc1033;"
                    type="text"
                    size="small"
                  >移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="12">
            <p style="font-size: 16px;">
              押金/保证金项目
              <el-button @click="addpressingGold" type="primary" size="mini">新增</el-button>
            </p>

            <el-dialog :visible.sync="pressingDialog" width="45%">
              <p style="font-size: 20px;">新增押金/保证金</p>
              <el-form :model="pressingModel" label-width="120px">
                <el-form-item label="押金项金额(元)：" prop="pressingGoldValue">
                  <el-input v-model="pressingModel.pressingGoldValue"></el-input>
                </el-form-item>
                <el-form-item label="押金项名称：" prop="pressingGoldName">
                  <el-input v-model="pressingModel.pressingGoldName"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="pressingClose">不保存押金项</el-button>
                <el-button type="primary" @click="savePressing">保存押金项</el-button>
              </span>
            </el-dialog>
            <el-table :data="pressingTableArray" style="width: 85%">
              <el-table-column prop="pressingGoldValue" label="押金项金额(元)"></el-table-column>
              <el-table-column prop="pressingGoldName" label="押金项名称"></el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="pressingDelete(scope.$index, pressingTableArray)"
                    style="color:#dc1033;"
                    type="text"
                    size="small"
                  >移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <el-row style="margin-bottom: 30px;">
          <el-col :span="8" style="color: #fff;">0</el-col>
          <el-col :span="8">
            <el-button
              type="primary"
              native-type="submit"
              style="background: #004e66;margin-top: 50px;"
            >保存</el-button>
          </el-col>
          <el-col :span="8" style="color: #fff;">0</el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-dialog :visible.sync="imgdialog" width="30%">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import MySelect from "@/components/MySelect";
import { formatDate2, isNil } from "@/utils";

export default {
  data() {
    return {
      qwe: true,
      uploadToken: {
        key: "",
        token: ""
      },
      ishidden: -1,
      imgdialog: false,
      dialogImageUrl: "",
      count:1,
      model: {
        renewContractId: 0, //   续签合同id，新增时为0
        signDate: formatDate2(new Date()), //		string	true	签订日期
        dueTime: "", //		date	true	到期时间
        businessId: 0, //	int	商户id
        businessName: "", //	string	商户名称
        personInCharge: "", // 联系人
        // stallId: 0, //	int	摊位id
        stallIds: "", // string	true	摊位ids	多个英文逗号分隔
        // stallName: '', //	string	摊位名称
        phone: "", //	string	手机号
        // partitionId: '', //	string	区域id
        // partitionName: '', //	string	区域名称
        contractNumber: "", //		string	true	合同编号

        photoUrl: "", //	string	true	合同图片地址
        paymentTypeName: "", // 收费名称

        // 最后要提交的 json 所有新增的收费项目
        payService: [],

        contractPhoto: [], // json	true	合同图片

        // 押金/保证金
        pressingGold: [] //		json	true	押金项
      },

      tableArray: [], // 表格数据
      tableModel: {
        price: 0, //	int	true	单价
        paymentTimeTypeName: formatDate2(new Date()), //	string	true	缴费时间(名称)
        paymentTypeName: "", // 收费名称
        paymentTypeId: "", //	int	true	收费项目基础表id
        unit: "", //	string	true	单位
        paymentTimeType: "", //	string	true	缴费时间(标志)
        timePos: "", //	int	true	计费头尾 0.未设置 1.头 2.尾
        months: "", //	string	true	月份，如：1,4,7,10
        day: "" //	int	true	天
      },

      // 固定收费项目
      paymentTypeList: [], // 收费项目
      isShow: false,
      paymentName: "", // 是什么费用
      paymentTypeDataArray: [], // 数据源 数组
      dialogVisible: false,

      // 押金/保证金
      //        pressingGold: [], //		json	true	押金项
      pressingModel: {
        pressingGoldName: "", //	string	true	押金项名称
        pressingGoldValue: "" //	string	true	押金项金额
      },
      pressingDialog: false,
      pressingTableArray: [],
      pressingIsShow: false
    };
  },
  components: {
    MySelect
  },
  watch: {
    "$store.state.app.marketId"(val, oldVal) {
      let date = new Date();
      let year = date.getFullYear();
      let mon = date.getMonth() + 12;
      let day = date.getDate();
      if (mon > 11) {
        year = year + 1;
        mon = date.getMonth() + 1;
      }
      if (mon < 10) {
        mon = "0" + mon;
      }
      if (day < 10) {
        day = "0" + day;
      }
      this.model.dueTime = year + "-" + mon + "-" + day;
      this.model.renewContractId = this.$route.query.renewContractId;
      this.goodsToken();
      this.getPaymentType(this.model.paymentTypeName);
      this.fetch(this.model.renewContractId);
    }
  },
  mounted() {
    let date = new Date();
    let year = date.getFullYear();
    let mon = date.getMonth() + 12;
    let day = date.getDate();
    if (mon > 11) {
      year = year + 1;
      mon = date.getMonth() + 1;
    }
    if (mon < 10) {
      mon = "0" + mon;
    }
    if (day < 10) {
      day = "0" + day;
    }
    this.model.dueTime = year + "-" + mon + "-" + day;
    //      console.log(this.$route.query.renewContractId)
    this.model.renewContractId = this.$route.query.renewContractId;
    this.goodsToken();
    this.getPaymentType(this.model.paymentTypeName);
    this.fetch(this.model.renewContractId);
    // lothis.model.renewContractId
    console.log(this.model.contractPhoto);
  },
  methods: {
    abc() {
      this.qwe = false;
    },
    changeSignDate(date) {
      this.model.signDate = formatDate2(date);
    },
    changeDueTime(date) {
      this.model.dueTime = formatDate2(date);
    },

    // 押金/保证金
    addpressingGold() {
      this.pressingDialog = true;
    },
    // 移除
    pressingDelete(index, rows) {
      console.log(rows);
      rows.splice(index, 1);
      this.model.pressingGold = JSON.stringify(this.pressingTableArray);
    },
    pressingClose() {
      this.pressingDialog = false;
      this.pressingModel = {};
    },

    savePressing() {
      /*this.pressingDialog = false
        let pressingGold = []
        pressingGold.push(this.pressingModel)
        this.model.pressingGold = JSON.stringify(pressingGold)
        this.pressingModel = {}*/

      this.pressingDialog = false;
      this.pressingIsShow = true;

      let temp = JSON.parse(JSON.stringify(this.pressingModel));
      this.pressingTableArray.push(temp);
      this.pressingModel = {};

      let tempArrays = JSON.parse(JSON.stringify(this.pressingTableArray));
      for (var i = 0; i < tempArrays.length; i++) {
        tempArrays[i].pressingGoldValue = tempArrays[i].pressingGoldValue * 100;
      }

      this.model.pressingGold = JSON.stringify(tempArrays);
    },

    // 收费项目

    // 数组去重
    unique(arr) {
      return Array.from(new Set(arr));
    },
    // 点击 加号
    addpayment() {
      this.dialogVisible = true;
    },
    changePaymentTime(date) {
      this.tableModel.paymentTimeTypeName = formatDate2(date);
    },
    // 删除 表格 收费项目
    paymentDelete(index, rows) {
      console.log(rows);
      rows.splice(index, 1);
      this.model.payService = JSON.stringify(this.tableArray);
    },

    // 保存一项一项
    saveArray() {
      this.dialogVisible = false;
      this.isShow = true;
      // console.log('this.tableModel')
      // console.log(this.tableModel)
      let temp = JSON.parse(JSON.stringify(this.tableModel));
      this.tableArray.push(temp);
      console.log("0 新添加的数组数据", this.tableArray);
      let tempArrays = JSON.parse(JSON.stringify(this.tableArray));
      for (var i = 0; i < tempArrays.length; i++) {
        tempArrays[i].price = tempArrays[i].price * 100;
      }

      this.model.payService = JSON.stringify(tempArrays);
    },

    // 取消 一项
    handleClose(done) {
      this.dialogVisible = false;
    },
    changePaymentType(type) {
      let obj = {};
      obj = this.paymentTypeDataArray.find(item => {
        // 这里的 this.paymentTypeDataArray 就是上面遍历的数据源
        return item.paymentTypeId === type / 1; // 筛选出匹配数据 数据源里的 type 等于 当前选中的 paymentTypeName
      });
      // Object.assign(obj, this.tableModel)
      this.tableModel = JSON.parse(JSON.stringify(obj));
      this.tableModel.price = obj.price / 100;
      this.model.paymentTypeName = obj.paymentTypeName;
    },
    // 获取 收费项目 类型
    getPaymentType(searchName) {
      this.$store
        .dispatch("contract/fetchPaymentType", { searchName })
        .then(data => {
          this.paymentTypeDataArray = data.items;
          let items = [];
          for (let item of data.items) {
            items.push({
              value: item.paymentTypeId + "",
              label: item.paymentTypeName
            });
          }
          this.paymentTypeList = items;
        })
        .catch(err => {
          this.paymentTypeList = [];
        });
    },

    // 选择商户 商户信息
    mySelectedBusiness(obj) {
      this.model.businessId = obj.value;
      this.model.businessName = obj.label;
      this.model.phone = obj.exData.phone;
      this.model.personInCharge = obj.exData.personInCharge;
    },
    // 摊位 自动完成
    mySelectedStall(arr) {
      this.model.stallIds = arr.join(",");
    },

    handleSuccessphotoUrl(res, file, fileList) {
      this.model.photoUrl = "http://cailanzi.image.cailanzi001.com/" + res.key;
      //  this.model.contractPhoto = JSON.parse(this.model.contractPhoto);
      // console.log(this.model.contractPhoto);
      // this.model.contractPhoto.push({photoUrl:this.model.photoUrl});
      this.model.contractPhoto.splice(this.model.contractPhoto.length,0,{photoUrl:this.model.photoUrl,keyindex:"new"+this.count})
      this.$forceUpdate()
      this.count++
      // this.model.contractPhoto = JSON.stringify(this.model.contractPhoto)
      // console.log(this.model.contractPhoto);
      // this.$refs.photoUrl.clearFiles()
    },

    handleRemove(file, fileList) {
      // console.log(file,fileList[0])
      // this.model.contractPhoto = JSON.parse(this.model.contractPhoto);
      this.model.contractPhoto.pop();
      this.$forceUpdate()
      // console.log(this.model.contractPhoto);
    },
    beforeUpload(file) {
      const isPNG = file.type === "image/png";
      const isJPEG = file.type === "image/jpeg";
      const isJPG = file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPNG && !isJPEG && !isJPG) {
        this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      //将上传的文件名保存成key,把这个key拼接到外链地址
      const date = new Date();
      this.uploadToken.key = `bill${date.getFullYear()}${date.getMonth() +
        1}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}${Math.floor(
        Math.random() * 100
      )}.${file.type.split("/")[1]}`;
    },
    //获取上传文件时候的token
    goodsToken() {
      this.$store
        .dispatch("purchaseInfo/uptoken", {})
        .then(data => {
          this.uploadToken.token = data.data.uptoken;
        })
        .catch(err => {});
    },

    // 提交先判断下， 新增 还是 续签 合同
    async save() {
      this.model.renewContractId = this.model.id;
      this.model.contractPhoto = JSON.stringify(this.model.contractPhoto);
      this.$store
        .dispatch("contract/fetchContractAddSave", this.model)
        .then(data => {
          if (data) {
            this.$router.push("/property/contract");
            this.$message({
              type: "success",
              message: "保存成功"
            });
            this.$refs["mySelectBusiness"].clear();
            this.$refs["mySelectStallName"].clear();
          }
        })
        .catch(err => {
          this.$message({
            type: "warning",
            message: "修改未完成"
          });
        });
    },
    // 如果是续签, 先获取详情, 填入表单里
    async fetch(renewContractId) {
      this.$store
        .dispatch("contract/fetchContractDetails", { renewContractId })
        .then(data => {
          this.model = data;
          this.model.contractPhoto = [];
          for (let i = 0; i < data.hasContractPhoto.length; i++) {
            this.model.contractPhoto.push({
              photoUrl: data.hasContractPhoto[i].photoUrl,
              keyindex: i+1
            });
          }
          // console.log(this.model.contractPhoto);
          for (var i = 0; i < data.hasPayService.length; i++) {
            data.hasPayService[i].price = data.hasPayService[i].price / 100;
          }
          this.model.payService = JSON.stringify(data.hasPayService);

          for (var i = 0; i < data.hasPressingGold.length; i++) {
            data.hasPressingGold[i].pressingGoldValue =
              data.hasPressingGold[i].pressingGoldValue / 100;
          }
          this.model.pressingGold = JSON.stringify(data.hasPressingGold);
          this.tableArray = data.hasPayService;
          this.model.photoUrl = data.hasContractPhoto[0].photoUrl;
          this.pressingTableArray = data.hasPressingGold;
          this.model.stallName = data.stallName;
        });
    },
    imgdelete(keyindex, index) {
      this.model.contractPhoto.splice(index, 1);
      this.ishidden = keyindex;
      // console.log("删除", index, this.model.contractPhoto);
    },
    imgshow(index) {
      this.dialogImageUrl = this.model.contractPhoto[index].photoUrl;
      this.imgdialog = true;
    }
  },
  create() {
    this.fetch(this.model.renewContractId);
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-input__inner {
  width: 194px;
}
/deep/ .el-upload--picture-card {
  background-color: white;
  border: none;
}
.button {
  background: #64d9d6;
  color: #fff;
  margin-left: 40px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.queryimg {
  font-size: 13px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.imgfile {
 width: 50%;
}
.hidden {
  display: none;
}
</style>
